package cc.md888.app.infr.ip.provider.ip123;

import cc.md888.app.infr.ip.IpInfoProvider;
import cc.md888.app.infr.ip.IpInfoVO;
import cc.md888.app.infr.ip.convert.Ip123Convert;
import cc.md888.app.utils.HttpUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Component
public class Ip123Provider implements IpInfoProvider {

    private final Ip123Convert convert = new Ip123Convert();

    @Override
    public IpInfoVO get(String ip) {
        String url = UriComponentsBuilder.fromHttpUrl("http://ip234.in/search_ip")
                .queryParam("ip", ip)
                .build().toUriString();

        Map<String, String> headers = new HashMap<>();
        headers.put("Accept", "application/json");
        headers.put("Content-Type", "application/json");

        try{
            String body = HttpUtils.get(url,  headers, null);
            JSONObject response = JSON.parseObject(body);
            String code = response.getString("code");
            if(!Objects.equals(code, "0")){
                log.error("get from ip123 error: {}", body);
                return null;
            }

            return convert.convert(response.getString("data"));
        }catch (Exception e){
            log.error(e.getMessage());
        }

        return null;
    }

    public static void main(String[] args) {
        System.out.println(new Ip123Provider().get("120.226.116.82"));
    }
}
